<?php
class BaseModel extends CActiveRecord
{
    public static $connections = array();
    //TODO lang和dbname用静态变量表示是不对的，应该跟着对象走。
    //TODO setLang 也有问题
    private static $lang='';
    private static $dbname='';
    public function getDbConnection()
    {
        if(!self::$dbname)
            self::setLang();
        $dbname = self::$dbname;
        if(!isset(self::$connections[$dbname]))
        {
            $dsn = sprintf(Yii::app()->params['dsn'],$dbname);
            self::$connections[$dbname] = new CDbConnection($dsn,Yii::app()->params['dbuser'],Yii::app()->params['dbpwd']);
            self::$connections[$dbname]->active=true;
        }
        return self::$connections[$dbname];
    }

    public static function setLang($lang='')
    {
        self::$lang = trim(strtolower($lang));
        if(!self::$lang)
            self::$lang = Yii::app()->params['default_language'];
        self::$dbname = Yii::app()->params['dbprefix'].self::$lang;
        if(!self::db_exists(self::$dbname))
        {
           throw new Exception("DB '".self::$dbname."' not exist", 1);
        }
    }

    public static function getLang()
    {
        return self::$lang;
    }
    public static function getDBNames()
    {
        $dbnames = Yii::app()->cache->get('all_db_names');
        if(!$dbnames || empty($dbnames))
        {
            $dbnames = Yii::app()->db->createCommand('show databases')->queryColumn();
            Yii::app()->cache->set('all_db_names',$dbnames,600);
        }
        return $dbnames;
    }
    public static function db_exists($dbname)
    {
        return in_array($dbname, self::getDBNames());
    }

    public static function getNewInstance($classname,$lang)
    {
        self::setLang($lang);
        return new $classname;
    }
    
    public static function getModel($classname,$lang)
    {
        self::setLang($lang);
        return $classname::model();
    }
}